﻿/*
*┌────────────────────────────────────────────────┐
*│　描    述：DealHttpDataBLL                                                   
*│　作    者： (Jxw)                                             
*│　版    本：1.0                                              
*│　创建时间：2020/7/7 14:34:39                        
*└────────────────────────────────────────────────┘
*/
using DAL;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using System.Web.Script.Serialization;
using System.Windows.Forms;
using Utility;

namespace BLL
{
    /// <summary>
    /// http请求处理
    /// </summary>
    public class DealHttpDataBLL
    {
        private HttpListenerRequest request;
        private HttpListenerResponse response;
        public static ResponseDataDTO responseDataDTO = new ResponseDataDTO() { status = ResultCode.Success };
        public static ResponsePageDTO pageDTO = new ResponsePageDTO() { status = ResultCode.Success };
        public static RetInfo<List<Hashtable>> hsList = new RetInfo<List<Hashtable>>(true);
        public static RetInfo<Hashtable> hashTable = new RetInfo<Hashtable>(true);
        public static HospitalBLL bll = new HospitalBLL();
        public static HospitalInfoDAL dal = new HospitalInfoDAL();
        public static string typeName;
        public static string areaName;

        public DealHttpDataBLL(HttpListenerRequest Request1, HttpListenerResponse Response1)
        {
            //允许跨域访问
            Response1.AddHeader("Access-Control-Allow-Origin", "*");
            Response1.AddHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
            Response1.ContentType = "multipart/form-data;charset=UTF-8";
            //Response1.AddHeader("Content-type", "text/plain");
            request = Request1;
            response = Response1;
        }


        /// <summary>
        /// 接收http请求消息处理
        /// </summary>
        public void ReceiveHttpData()
        {
            //接收客户端传过来的数据并转成字符串类型
            Stream body = request.InputStream; //获取客户端发送请求的包含正文数据的流
            //接收客户端传过来的数据并转成字符串类型
            Encoding encoding = request.ContentEncoding;  //获取随请求发送的数据的内容编码
            StreamReader reader = null;
            string bodyStr = "";
            try
            {
                reader = new StreamReader(body, Encoding.UTF8); //用指定的字符编码为指定的流初始化 System.IO.StreamReader 类的一个新实例。
                bodyStr = reader.ReadToEnd(); //读取流，返回字符串
                if (bodyStr.Trim() != "")
                {
                    NameValueCollection query = HttpUtility.ParseQueryString(bodyStr, Encoding.UTF8);
                    string messageTypeValue = query["MessageType"];
                    OnShowMessage(AnchorEnum.EMessageLevel.EML_INFO, "收到http请求推送的数据：" + query);
                    LogUtility.Debug("DealHttpDataBLL/ReceiveHttpData", "收到http请求推送的数据：" + query); //记录日志

                    #region 正则表达式
                    //提取decoderContent中的MessageType值
                    //string messageTypeValue = Common.ReularValue("MessageType", decoderContent);

                    #endregion

                    OnShowMessage(AnchorEnum.EMessageLevel.EML_INFO, "收到http请求,请求消息类型：" + messageTypeValue);//只显示请求的类型信息
                    LogUtility.Debug("DealHttpDataBLL/ReceiveHttpData", "收到http请求,请求消息类型：" + messageTypeValue);


                    switch (messageTypeValue)//判断请求消息类型
                    {
                        case "GetAmbulanceList": //获取车组信息的接口
                            responseDataDTO = dal.GetAmbulanceList();
                            ReturnHttpData(responseDataDTO, response); //返回响应消息--处理结果
                            break;
                        case "GetCenterList": //获取中心信息的接口
                            typeName = query["typeName"];
                            hsList = dal.GetCenterList(typeName);
                            ReturnHttpData(hsList, response); //返回响应消息--处理结果
                            break;
                        case "GetHospitalList": //获取医院信息的接口
                            responseDataDTO = dal.GetHospitalList();
                            ReturnHttpData(responseDataDTO, response); //返回响应消息--处理结果
                            break;
                        case "GetHospitalXY": //获取医院信息的接口
                            areaName = query["areaName"];
                            responseDataDTO = dal.GetHospitalXY(areaName);
                            ReturnHttpData(responseDataDTO, response); //返回响应消息--处理结果
                            break;
                        case "GetAreaAmbList": //获取区域车组信息的接口
                            areaName = query["areaName"];
                            responseDataDTO = dal.GetAreaAmbList(areaName);
                            ReturnHttpData(responseDataDTO, response); //返回响应消息--处理结果
                            break;
                        case "GetToldStatistics": //获取衔接接送统计的接口
                            responseDataDTO = dal.GetToldStatistics();
                            ReturnHttpData(responseDataDTO, response); //返回响应消息--处理结果
                            break;
                        case "GetDiseaseLevelList": //获取衔接接送统计的接口
                            typeName = query["typeName"];
                            responseDataDTO = dal.GetDiseaseLevelList(typeName);
                            ReturnHttpData(responseDataDTO, response); //返回响应消息--处理结果
                            break;
                        case "GetDiseaseTypeList": //获取衔接接送统计的接口
                            typeName = query["typeName"];
                            responseDataDTO = dal.GetDiseaseTypeList(typeName);
                            ReturnHttpData(responseDataDTO, response); //返回响应消息--处理结果
                            break;
                        case "GetHospitalInfo": //获取医院详情信息的接口
                            string id = query["id"];
                            responseDataDTO = dal.GetHospitalInfo(id);
                            ReturnHttpData(responseDataDTO, response); //返回响应消息--处理结果
                            break;
                        case "GetAmbulanceGPSList": //获取医院信息的接口
                            responseDataDTO = dal.GetAmbulanceGPSList();
                            ReturnHttpData(responseDataDTO, response); //返回响应消息--处理结果
                            break;
                        case "GetDictionaryList": //获取医院信息的接口
                            DictionaryBLL dictionaryBLL = new DictionaryBLL();
                            hsList= dictionaryBLL.GetDictionaryList();
                            ReturnHttpData(hsList, response); //返回响应消息--处理结果
                            break;
                        
                        //case "GetHospitalInfo": //获取医院信息的接口
                        //    string id = query["id"];
                        //    hashTable = bll.GetHospitalInfo(id);
                        //    ReturnHttpData(hashTable, response); //返回响应消息--处理结果
                        //    break;
                        default:
                            OnShowMessage(AnchorEnum.EMessageLevel.EML_ERROR, "http收到错误信息；消息类型：" + messageTypeValue);
                            LogUtility.Error("DealHttpDataBLL/ReceiveHttpData", "http收到错误信息；消息类型：" + messageTypeValue);//记日志
                            ReturnHttpData("错误信息,消息类型无法识别", response);
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                OnShowMessage(AnchorEnum.EMessageLevel.EML_ERROR, "Http请求协议解析处理错误[" + ex.Message + "]");
                LogUtility.Error("DealHttpDataBLL/ReceiveHttpData", "Http请求协议解析处理错误！[" + ex.Message + "]");
                ReturnHttpData("Http请求协议解析处理错误[" + ex.Message + "]", response);
            }
            finally
            {
                body.Close();
                reader.Close();
            }
        }




        /// <summary>
        /// 解析URL(可以正确识别UTF-8和GB2312编码)
        /// </summary>
        /// <param name="uriString"></param>
        /// <returns></returns>
        public string DecodeURL(String uriString)
        {
            return HttpUtility.UrlDecode(uriString, Encoding.GetEncoding("UTF-8"));
        }


        /// <summary>
        /// 返回响应消息
        /// </summary>
        /// <param name="data">返回的响应消息内容--一般是传入string字符串</param>
        /// <param name="response">HttpListenerResponse</param>
        public void ReturnHttpData(object data, HttpListenerResponse response)
        {
            try
            {

                System.Web.Script.Serialization.JavaScriptSerializer jser = new System.Web.Script.Serialization.JavaScriptSerializer();
                string responseString = jser.Serialize(data);
                byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString); //将string中所有字符编码为字节序列
                response.ContentLength64 = buffer.Length; //字节数
                System.IO.Stream output = response.OutputStream; //将响应写入其中的 System.IO.Stream 对象。
                output.Write(buffer, 0, buffer.Length);//向当前流中写入字节序列，并将此流中的当前位置提升写入的字节数---写入响应内容
                output.Close();//关闭当前流
            }
            catch (Exception ex)
            {
                OnShowMessage(AnchorEnum.EMessageLevel.EML_INFO, "回复信息失败：" + ex.Message);
                LogUtility.Error("DealHttpDataBLL/ReturnHttpData", "回复信息失败！[" + ex.Message + "]");
            }

        }

        /// <summary>
        /// 返回响应消息
        /// </summary>
        /// <param name="data">返回的响应消息内容---一般是传入要序列化为JSON字符串的对象</param>
        /// <param name="response">HttpListenerResponse</param>
        public void ReturnHttpDataWithSerial(object data, HttpListenerResponse response)
        {
            try
            {
                System.Web.Script.Serialization.JavaScriptSerializer jser = new System.Web.Script.Serialization.JavaScriptSerializer();
                string responseString = jser.Serialize(data);
                byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
                response.ContentLength64 = buffer.Length;
                System.IO.Stream output = response.OutputStream;
                output.Write(buffer, 0, buffer.Length);
                output.Close();
            }
            catch (Exception ex)
            {
                OnShowMessage(AnchorEnum.EMessageLevel.EML_ERROR, "回复信息失败！[" + ex.Message + "]");
                LogUtility.Error("DealHttpDataBLL/ReturnHttpDataWithSerial", "回复信息失败！[" + ex.Message + "]");
            }

        }


        #region 委托

        /// <summary>
        /// 显示消息委托
        /// </summary>
        /// <param name="messageLevel"></param>
        /// <param name="msg"></param>
        public delegate void ShowMessageHandler(AnchorEnum.EMessageLevel messageLevel, string message);
        public event ShowMessageHandler ShowMessage;
        private void OnShowMessage(AnchorEnum.EMessageLevel messageLevel, string message)
        {
            if (ShowMessage != null)
            {
                Control target = ShowMessage.Target as Control;
                if (target != null && target.InvokeRequired)
                    target.BeginInvoke(ShowMessage, new object[] { messageLevel, message });
                else
                    ShowMessage(messageLevel, message);
            }
        }

        #endregion


    }
}
